import 'package:get/get.dart';
import '../data/models/emotion_record.dart';
import '../data/models/analytics_models.dart';
import '../data/models/statistics_summary.dart' as stats;
import '../data/repositories/emotion_repository.dart';
import '../data/repositories/emotion_repository_impl.dart';

/// 趋势分析控制器
/// Analytics controller
class AnalyticsController extends GetxController {
  final EmotionRepository _emotionRepository = EmotionRepositoryImpl();

  // 响应式状态变量
  // Reactive state variables
  final RxList<EmotionTrend> _emotionTrends = <EmotionTrend>[].obs;
  final RxList<EmotionDistribution> _emotionDistribution = <EmotionDistribution>[].obs;
  final RxList<IntensityDistribution> _intensityDistribution = <IntensityDistribution>[].obs;
  final RxList<WordFrequency> _wordFrequencies = <WordFrequency>[].obs;
  final Rx<stats.StatisticsSummary?> _statisticsSummary = Rx<stats.StatisticsSummary?>(null);
  final Rx<DateRange> _currentDateRange = DateRange(
    startDate: DateTime.now().subtract(const Duration(days: 30)),
    endDate: DateTime.now(),
  ).obs;
  final RxBool _isLoading = false.obs;
  final RxString _errorMessage = ''.obs;
  final RxString _selectedAnalyticsType = 'trend'.obs; // trend, distribution, wordcloud
  final RxInt _selectedDays = 30.obs; // 选中的天数

  // Getters for accessing reactive state
  List<EmotionTrend> get emotionTrends => _emotionTrends;
  List<EmotionDistribution> get emotionDistribution => _emotionDistribution;
  List<IntensityDistribution> get intensityDistribution => _intensityDistribution;
  List<WordFrequency> get wordFrequencies => _wordFrequencies;
  stats.StatisticsSummary? get statisticsSummary => _statisticsSummary.value;
  DateRange get currentDateRange => _currentDateRange.value;
  bool get isLoading => _isLoading.value;
  String get errorMessage => _errorMessage.value;
  String get selectedAnalyticsType => _selectedAnalyticsType.value;
  int get selectedDays => _selectedDays.value;

  @override
  void onInit() {
    super.onInit();
    // 初始化时加载数据
    // Load data on initialization
    loadAllAnalyticsData();
  }

  /// 加载所有分析数据
  /// Load all analytics data
  Future<void> loadAllAnalyticsData() async {
    await Future.wait([
      loadEmotionTrends(),
      loadEmotionDistribution(),
      loadWordFrequencies(),
      loadStatisticsSummary(),
    ]);
  }

  /// 加载情绪趋势数据
  /// Load emotion trend data
  Future<void> loadEmotionTrends() async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      final trends = await _emotionRepository.getEmotionTrends(
        dateRange: _currentDateRange.value,
      );
      _emotionTrends.assignAll(trends);
    } catch (e) {
      _errorMessage.value = '加载情绪趋势失败: ${e.toString()}';
      Get.snackbar('错误', '加载情绪趋势失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 加载情绪分布数据
  /// Load emotion distribution data
  Future<void> loadEmotionDistribution() async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      final distribution = await _emotionRepository.getEmotionDistribution(
        dateRange: _currentDateRange.value,
      );
      _emotionDistribution.assignAll(distribution);
    } catch (e) {
      _errorMessage.value = '加载情绪分布失败: ${e.toString()}';
      Get.snackbar('错误', '加载情绪分布失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 加载词频数据
  /// Load word frequency data
  Future<void> loadWordFrequencies({int limit = 50}) async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      final frequencies = await _emotionRepository.getWordFrequencies(
        dateRange: _currentDateRange.value,
        limit: limit,
      );
      _wordFrequencies.assignAll(frequencies);
    } catch (e) {
      _errorMessage.value = '加载词频数据失败: ${e.toString()}';
      Get.snackbar('错误', '加载词频数据失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 加载统计摘要
  /// Load statistics summary
  Future<void> loadStatisticsSummary() async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      final summary = await _emotionRepository.getStatisticsSummary();
      _statisticsSummary.value = summary;
    } catch (e) {
      _errorMessage.value = '加载统计摘要失败: ${e.toString()}';
      Get.snackbar('错误', '加载统计摘要失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 设置日期范围
  /// Set date range
  Future<void> setDateRange(DateTime startDate, DateTime endDate) async {
    _currentDateRange.value = DateRange(
      startDate: startDate,
      endDate: endDate,
    );
    
    // 重新加载数据
    // Reload data
    await loadAllAnalyticsData();
  }

  /// 设置预定义的日期范围
  /// Set predefined date range
  Future<void> setPredefinedDateRange(String range) async {
    final now = DateTime.now();
    DateTime startDate;
    DateTime endDate = now;
    
    switch (range) {
      case 'week':
        startDate = now.subtract(const Duration(days: 7));
        break;
      case 'month':
        startDate = now.subtract(const Duration(days: 30));
        break;
      case 'quarter':
        startDate = now.subtract(const Duration(days: 90));
        break;
      case 'year':
        startDate = now.subtract(const Duration(days: 365));
        break;
      default:
        startDate = now.subtract(const Duration(days: 30));
    }
    
    await setDateRange(startDate, endDate);
  }

  /// 设置选中的分析类型
  /// Set selected analytics type
  void setAnalyticsType(String type) {
    _selectedAnalyticsType.value = type;
  }

  /// 设置时间范围（天数）
  /// Set time range (days)
  Future<void> setTimeRange(int days) async {
    _selectedDays.value = days;
    
    // 根据天数设置日期范围
    // Set date range based on days
    final now = DateTime.now();
    DateTime startDate;
    
    if (days == -1) {
      // 全部数据
      startDate = DateTime(2020, 1, 1); // 设置一个足够早的日期
    } else {
      startDate = now.subtract(Duration(days: days));
    }
    
    await setDateRange(startDate, now);
    update(); // 通知GetBuilder更新UI
  }

  /// 获取情绪趋势图表数据
  /// Get emotion trend chart data
  List<Map<String, dynamic>> getTrendChartData() {
    return _emotionTrends.map((trend) => {
      'date': trend.date,
      'intensity': trend.averageIntensity,
      'count': trend.recordCount,
    }).toList();
  }

  /// 获取情绪分布饼图数据
  /// Get emotion distribution pie chart data
  List<Map<String, dynamic>> getDistributionChartData() {
    return _emotionDistribution.map((distribution) => {
      'emotion': distribution.emotionType.label,
      'count': distribution.count,
      'percentage': distribution.percentage,
      'color': _getEmotionColor(distribution.emotionType),
    }).toList();
  }

  /// 获取词云数据
  /// Get word cloud data
  List<Map<String, dynamic>> getWordCloudData() {
    return _wordFrequencies.map((frequency) => {
      'word': frequency.word,
      'frequency': frequency.frequency,
      'size': _calculateWordSize(frequency.frequency),
    }).toList();
  }

  /// 获取情绪对应的颜色
  /// Get color for emotion type
  String _getEmotionColor(EmotionType emotionType) {
    switch (emotionType) {
      case EmotionType.happy:
        return '#FFD700'; // 金黄色
      case EmotionType.sad:
        return '#87CEEB'; // 天蓝色
      case EmotionType.angry:
        return '#FF6B6B'; // 红色
      case EmotionType.anxious:
        return '#DDA0DD'; // 紫色
      case EmotionType.excited:
        return '#FF69B4'; // 粉色
      case EmotionType.calm:
        return '#98FB98'; // 淡绿色
      case EmotionType.grateful:
        return '#F0E68C'; // 卡其色
      case EmotionType.content:
        return '#E6E6FA'; // 薰衣草色
      case EmotionType.tired:
        return '#B0C4DE'; // 淡钢蓝色
      case EmotionType.confused:
        return '#DDA0DD'; // 梅花色
      case EmotionType.lonely:
        return '#778899'; // 淡石板灰
      default:
        return '#D3D3D3'; // 浅灰色
    }
  }

  /// 计算词云中单词的大小
  /// Calculate word size in word cloud
  double _calculateWordSize(int frequency) {
    if (_wordFrequencies.isEmpty) return 12.0;
    
    final maxFrequency = _wordFrequencies.first.frequency;
    final minFrequency = _wordFrequencies.last.frequency;
    
    if (maxFrequency == minFrequency) return 16.0;
    
    // 将频率映射到12-24的字体大小范围
    // Map frequency to font size range 12-24
    final ratio = (frequency - minFrequency) / (maxFrequency - minFrequency);
    return 12.0 + (ratio * 12.0);
  }

  /// 获取情绪强度的平均值
  /// Get average emotion intensity
  double getAverageIntensity() {
    if (_emotionTrends.isEmpty) return 0.0;
    
    final totalIntensity = _emotionTrends.fold<double>(
      0.0,
      (sum, trend) => sum + trend.averageIntensity,
    );
    
    return totalIntensity / _emotionTrends.length;
  }

  /// 获取最活跃的记录日期
  /// Get most active recording date
  DateTime? getMostActiveDate() {
    if (_emotionTrends.isEmpty) return null;
    
    EmotionTrend mostActive = _emotionTrends.first;
    for (final trend in _emotionTrends) {
      if (trend.recordCount > mostActive.recordCount) {
        mostActive = trend;
      }
    }
    
    return mostActive.date;
  }

  /// 获取最常见的情绪类型
  /// Get most common emotion type
  EmotionType? getMostCommonEmotion() {
    if (_emotionDistribution.isEmpty) return null;
    
    return _emotionDistribution.first.emotionType;
  }

  /// 获取情绪变化趋势（上升/下降/稳定）
  /// Get emotion change trend (rising/falling/stable)
  String getEmotionTrend() {
    if (_emotionTrends.length < 2) return '数据不足';
    
    final recentTrends = _emotionTrends.take(7).toList();
    if (recentTrends.length < 2) return '数据不足';
    
    final firstIntensity = recentTrends.last.averageIntensity;
    final lastIntensity = recentTrends.first.averageIntensity;
    
    final difference = lastIntensity - firstIntensity;
    
    if (difference > 0.5) {
      return '情绪呈上升趋势 📈';
    } else if (difference < -0.5) {
      return '情绪呈下降趋势 📉';
    } else {
      return '情绪保持稳定 ➡️';
    }
  }

  /// 刷新所有数据
  /// Refresh all data
  Future<void> refreshData() async {
    await loadAllAnalyticsData();
  }

  /// 清除错误信息
  /// Clear error message
  void clearError() {
    _errorMessage.value = '';
  }

  /// 导出分析报告
  /// Export analytics report
  Map<String, dynamic> exportAnalyticsReport() {
    return {
      'date_range': {
        'start_date': _currentDateRange.value.startDate.toIso8601String(),
        'end_date': _currentDateRange.value.endDate.toIso8601String(),
      },
      'statistics_summary': _statisticsSummary.value?.toJson(),
      'emotion_trends': _emotionTrends.map((trend) => trend.toJson()).toList(),
      'emotion_distribution': _emotionDistribution.map((dist) => dist.toJson()).toList(),
      'word_frequencies': _wordFrequencies.map((freq) => freq.toJson()).toList(),
      'insights': {
        'average_intensity': getAverageIntensity(),
        'most_active_date': getMostActiveDate()?.toIso8601String(),
        'most_common_emotion': getMostCommonEmotion()?.name,
        'emotion_trend': getEmotionTrend(),
      },
      'generated_at': DateTime.now().toIso8601String(),
    };
  }
}